package com.guldan.auth.common.base;

import com.guldan.auth.common.authentication.LoginUser;
import com.guldan.core.constants.CommonConstant;
import com.guldan.core.redis.CacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Silas.
 * Date: 2016/10/1
 * Time: 22:41
 */
public class BaseController {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private CacheService cacheService;

    public boolean authLogin(String username, String password, String JSESSIONID) {
        boolean result = false;
        if (password.equals("123456")) {
            result = true;

            if (LoginUser.getLoginUser().containsKey(username))
                LoginUser.getLoginUser().replace(username, JSESSIONID);
            else
                LoginUser.getLoginUser().put(username, JSESSIONID);

            //login success and update redis map
            Map<Object, Object> users = cacheService.hMap(CommonConstant.KEY_LOGINUSER);
            if (users == null) {
                users = new HashMap<Object, Object>();
                users.put(username, JSESSIONID);
                cacheService.hputs(CommonConstant.KEY_LOGINUSER, (HashMap<? extends Object, ? extends Object>) users);
            } else if (!users.containsKey(username)) {
                cacheService.hput(CommonConstant.KEY_LOGINUSER, username, JSESSIONID);
            }
            logger.info("redis write success.[username=" + username + ", JSESSIONID=" + cacheService.hMap(CommonConstant.KEY_LOGINUSER).get(username) + "]");
        }
        return result;
    }

    public String getCookieValue(Cookie[] cookies, String name) {

        String ret = "";
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie c = cookies[i];
                if (name.equalsIgnoreCase(c.getName())) {
                    ret = c.getValue();
                }
            }
        }
        return ret;
    }
}
